Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Collections.Generic
Imports SubSonic
Imports ClubStarterKit.Data

Partial Class Admin_Email
    Inherits System.Web.UI.Page

    Private strPath As String = Server.MapPath("~\Files") & "\"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            chkRecipients.DataSource = Roles.GetAllRoles
            chkRecipients.DataBind()
        End If
    End Sub

    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click
        Dim recipientChecked As Boolean = False
        For Each item As ListItem In chkRecipients.Items
            If item.Selected Then
                recipientChecked = True
                Exit For
            End If
        Next

        If recipientChecked = False Then
            If chkAllMembers.Checked = False Then
                lblError.Text = "No recipients selected."
                lblError.Visible = True
                Return
            End If
        Else
            lblError.Text = ""
            lblError.Visible = False
        End If
        If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
        Else
            fileUpload_Click(Me, System.EventArgs.Empty)
        End If

        Dim haveAttachment As Boolean = False
        Dim strFiles() As String = Nothing

        If txtAttachments.Text.Length > 0 Then
            strFiles = Split(txtAttachments.Text, ControlChars.NewLine)
            haveAttachment = True
        End If

        Dim ToAddresses As MailAddressCollection = GetRecipients()

        Dim mem As MembershipUser = Membership.GetUser()
        Dim gui As New Guid(mem.ProviderUserKey.ToString)
        Dim name As String = GetName(gui)
        Dim msgFrom As New MailAddress(mem.Email.ToString(), name.ToString())
        Dim msgMail As New MailMessage(msgFrom, msgFrom)

        For Each msgTo As MailAddress In ToAddresses
            msgMail.To.Add(msgTo)
        Next

        msgMail.Subject = txtSubject.Text

        msgMail.IsBodyHtml = True
        msgMail.Body = FCKeditor1.Value

        If haveAttachment Then
            Dim str As String
            For Each str In strFiles
                If str = "" Then Continue For
                msgMail.Attachments.Add(New Attachment(strPath & str))
            Next
        End If
        Dim smtp As New SmtpClient(ClubStarterKit.Web.Settings.MailServer())
        Dim a As New Net.NetworkCredential(ClubStarterKit.Web.Settings.MailUsername(), ClubStarterKit.Web.Settings.MailPassword())
        smtp.UseDefaultCredentials = False
        smtp.Credentials = a
        smtp.Send(msgMail)
        Response.Redirect("~/default.aspx")
    End Sub

    Protected Sub fileUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles fileUpload.Click
        If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
            Return
        Else
            Dim strFileName As String = AttachmentFile.FileName
            Dim c As String = System.IO.Path.GetFileName(strFileName)

            Try

                txtAttachments.Visible = True
                AttachmentFile.PostedFile.SaveAs(strPath & c)
                txtAttachments.Text &= c & ControlChars.NewLine
            Catch Exp As Exception
                Throw Exp
            End Try
        End If
    End Sub

    Private Function GetName(ByVal userid As Guid) As String
        Return ClubStarterKit.Web.Members.FirstAndLastName(userid)
    End Function

    Protected Function GetRecipients() As MailAddressCollection
        Dim retval As New MailAddressCollection
        If chkAllMembers.Checked Then
            Dim mem As MembershipUser
            For Each mem In Membership.GetAllUsers
                Dim gui As New Guid(mem.ProviderUserKey.ToString)
                Dim name As String = GetName(gui)
                If name = "" Then
                    name = "-"
                End If
                Dim address As New MailAddress(mem.Email, name)
                Dim user As MembershipUser = Membership.GetUser(gui)
                Dim MemInfo As New MemberInfo(MemberInfo.Columns.Memberid, user.ProviderUserKey)
                If MemInfo.IsLoaded = True AndAlso CBool(MemInfo.Newsletter) = True Then
                    retval.Add(address)
                End If
            Next
        Else
            Dim selectedRoles As New List(Of String)
            For Each item As ListItem In chkRecipients.Items
                If item.Selected Then
                    selectedRoles.Add(item.Text)
                End If
            Next
            Dim usernames As New Collection

            Dim strUsernames() As String
            For Each selRole As String In selectedRoles
                strUsernames = Roles.GetUsersInRole(selRole)
                For Each Str As String In strUsernames
                    usernames.Add(Str)
                Next
            Next
            Dim mem As MembershipUser

            For Each str As String In usernames
                mem = Membership.GetUser(str)
                Dim gui As New Guid(mem.ProviderUserKey.ToString)
                Dim name As String = GetName(gui)
                Dim address As New MailAddress(mem.Email, name)
                Dim user As MembershipUser = Membership.GetUser(gui)
                Dim meminfo As New MemberInfo(MemberInfo.Columns.Memberid, user.ProviderUserKey)
                If meminfo.IsLoaded = True AndAlso CBool(meminfo.Newsletter) = True Then
                    retval.Add(address)
                End If
            Next
        End If
        Return retval
    End Function
End Class
